package com.happysunrise.nru.managers.imp;

import com.github.pagehelper.PageHelper;
import com.happysunrise.nru.daos.*;
import com.happysunrise.nru.enumerations.QueryOrderEnum;
import com.happysunrise.nru.enumerations.ResultTypeEnum;
import com.happysunrise.nru.managers.IUserManager;
import com.happysunrise.nru.models.*;
import com.happysunrise.nru.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 用户管理.
 * <p>
 * Created by liukaixin on 16/9/4.
 */
@Component
public class UserManager implements IUserManager {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(UserManager.class);

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IUserCompetitionDao userCompetitionDao;
    @Autowired
    private IUserTeamDao userTeamDao;
    @Autowired
    private IUserFavoriteDao userFavoriteDao;
    @Autowired
    private IApplyDao applyDao;

    /**
     * 登录.
     *
     * @param username 用户名
     * @return 用户
     */
    @Override
    public User login(String username) {
        try {
            return userDao.getUserByName(username);
        } catch (RuntimeException e) {
            LOGGER.error("login exception: ", e);
            return null;
        }
    }

    /**
     * 注册.
     *
     * @param user 用户
     * @return 添加条数
     */
    @Override
    public Integer register(User user) {
        try {
            user.setPic(getUrl());
            Integer code = userDao.addUser(user);
            if (code == 1) {
                return ResultTypeEnum.SUCCESS.getValue();
            } else {
                LOGGER.error("add user but code wasn't 1, code is [{}]", code);
                return ResultTypeEnum.FAILED.getValue();
            }
        } catch (DuplicateKeyException e) {
            LOGGER.debug("重复注册:", e);
            return ResultTypeEnum.DUPLICATE_USER_NAME.getValue();
        } catch (RuntimeException e) {
            LOGGER.error("add user exception: ", e);
            return ResultTypeEnum.FAILED.getValue();
        }
    }

    private String getUrl() {
        Random random = new Random();
        Integer num = random.nextInt(1257) % 1257 + 1;
        return "http://123.57.227.14:8686/user_pic/" + String.valueOf(num) + ".jpg";
    }

    @Override
    public Integer getUserNum() {
        try {
            return userDao.getUserCount();
        } catch (RuntimeException e) {
            LOGGER.error("get user count exception: ", e);
            return ResultTypeEnum.WRONG_USER_COUNT.getValue();
        }
    }

    /**
     * 添加我的竞赛
     *
     * @param competition 竞赛实体
     * @param userId      用户Id
     * @return
     */
    @Override
    public Integer addMyCompetition(Competition competition, Integer userId) {
        return userCompetitionDao.addMyCompetition(competition, userId);
    }

    /**
     * 添加我的团队
     *
     * @param team 我的团队
     * @return
     */
    @Override
    public Integer addMyTeam(UserTeam team) {
        return userTeamDao.addMyTeam(team);
    }

    /**
     * 获取我的团队
     *
     * @param page   页码
     * @param rows   条数
     * @param userId 用户Id
     * @return 团队列表
     */
    @Override
    public List<UserTeam> getTeamsByUserId(Integer page,
                                           Integer rows,
                                           Integer userId) {
        PageHelper.startPage(page, rows);
        PageHelper.orderBy(QueryOrderEnum
                .CREATE_TIME.getOrder());
        try {
            return userTeamDao
                    .getTeamsByUserId(userId);
        } catch (RuntimeException e) {
            LOGGER.error("getTeamsByUserId:", e);
            return new ArrayList<>();
        }
    }


    /**
     * 获取我的收藏
     *
     * @param page   页码
     * @param rows   条数
     * @param userId 用户Id
     * @return 收藏列表
     */
    @Override
    public List<Favorite> getFavoritesByUserId(Integer page,
                                               Integer rows,
                                               Integer userId) {
        PageHelper.startPage(page, rows);
        PageHelper.orderBy(QueryOrderEnum
                .CREATE_TIME.getOrder());
        try {
            return userFavoriteDao
                    .getFavoritesByUserId(userId);
        } catch (RuntimeException e) {
            LOGGER.error("getFavoritesByUserId:", e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据团队id和用户获取团队成员详情.
     *
     * @param teamId 团队id
     * @param userId 用户id
     * @return
     */
    @Override
    public User getUserByTeamIdAndUserId(Integer teamId, Integer userId) {
        User user = userDao.getUserById(userId);
        user.setAbility(applyDao
                .getApplyByTeamIdAndApplyUserId(teamId, userId).getAbility());

        return user;
    }

    /**
     * 根据用户id获取用户详情.
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public User getUserInfoById(Integer userId) {
        return userDao.getUserById(userId);
    }

    /**
     * 添加我的收藏 .
     *
     * @param favorite 我的收藏
     * @return
     */
    @Override
    public Integer favorite(Favorite favorite) {

        return userFavoriteDao.addFavorite(favorite);
    }

    @Override
    public Favorite getFavoriteByStarIdAndUserId(Integer starId, Integer userId) {
        Favorite favorite;
        favorite = userFavoriteDao.getFavoritesByStarIdAndUserId(starId, userId);
        return favorite;
    }

    @Override
    public Integer deleteFavorite(Integer starId, Integer userId) {
        return userFavoriteDao.deleteFavorite(starId, userId);
    }

    /**
     * 更新用户.
     *
     * @param user 用户
     * @return
     */
    @Override
    public Integer update(User user) {
        return userDao.update(user);
    }

    /**
     * 添加token.
     *
     * @param id    userId
     * @param token token
     * @return
     */
    @Override
    public Integer addToken(Integer id, String token) {
        try {
            return userDao.addToken(id, token);
        } catch (DuplicateKeyException e) {
            LOGGER.debug("token重复:", e);
            return userDao.updateToken(id, TokenUtil.getToken(id));
        }
    }

    @Override
    public User getUserNameAndPicById(Integer id) {
        try {
            return userDao.getUserNameAndPicById(id);
        } catch (RuntimeException e) {
            LOGGER.error("通过用户id获取用户名和用户图片", e);
            return null;
        }
    }

    /**
     * 添加用户推送.
     *
     * @param userPush 用户推送
     * @return
     */
    @Override
    public Integer addUserPush(UserPush userPush) {
        return userDao.addUserPush(userPush);
    }

    /**
     * 更新用户推送.
     *
     * @param userPush 用户推送
     * @return
     */
    @Override
    public Integer updateUserPush(UserPush userPush) {
        return userDao.updateUserPush(userPush);
    }

}
